package test01;

// OutputFilter.java - 输出统计结果
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

public class OutputFilter implements Filter {
    private OutputType outputType;
    private String outputFile;

    public enum OutputType {
        CONSOLE, FILE
    }

    public OutputFilter(OutputType outputType, String outputFile) {
        this.outputType = outputType;
        this.outputFile = outputFile;
    }

    @Override
    public Object process(Object input) {
        if (input == null) {
            return null;
        }

        StatisticsResult result = (StatisticsResult) input;
        String output = formatOutput(result);

        switch (outputType) {
            case CONSOLE:
                outputToConsole(output);
                break;
            case FILE:
                outputToFile(output);
                break;
        }

        return output;
    }

    private String formatOutput(StatisticsResult result) {
        StringBuilder sb = new StringBuilder();
        sb.append("=== 文本文件单词统计结果 ===\n");
        sb.append("总单词数: ").append(result.getTotalWords()).append("\n");
        sb.append("不同单词数: ").append(result.getWordFrequency().size()).append("\n\n");
        sb.append("单词频率统计:\n");

        result.getWordFrequency().entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .forEach(entry ->
                        sb.append(String.format("%-15s: %d次\n", entry.getKey(), entry.getValue())));

        return sb.toString();
    }

    private void outputToConsole(String output) {
        System.out.println("输出过滤器：将结果输出到控制台");
        System.out.println(output);
    }

    private void outputToFile(String output) {
        try (FileWriter writer = new FileWriter(outputFile)) {
            writer.write(output);
            System.out.println("输出过滤器：结果已保存到文件 '" + outputFile + "'");
        } catch (IOException e) {
            System.err.println("输出过滤器：写入文件失败 - " + e.getMessage());
        }
    }
}